학습목표

  1. beautifulsoup 모듈 사용하기
In [1]:
from bs4 import BeautifulSoup

html 문자열 파싱

  • 문자열로 정의된 html 데이터 파싱하기
In [2]:
html = '''
<html>
  <head>
    <title>BeautifulSoup test</title>
  </head>
  <body>
    <div id='upper' class='test' custom='good'>
      <h3 class='test2' title='Good Content Title'>Contents Title</h3>
      <p>Test contents</p>
      <h4>TEST</h4>
    </div>
    <div id='lower' class='test' custom='nice'>
      <p>Test Test Test 1</p>
      <p>Test Test Test 2</p>
      <p>Test Test Test 3</p>
    </div>
  </body>
</html>'''

find 함수

  • 특정 html tag를 검색
  • 검색 조건을 명시하여 찾고자하는 tag를 검색
In [3]:
soup = BeautifulSoup(html)
In [4]:
soup.find('h3')
Out[4]:
<h3 class="test2" title="Good Content Title">Contents Title</h3>
In [5]:
soup.find('div')
Out[5]:
<div class="test" custom="good" id="upper">
<h3 class="test2" title="Good Content Title">Contents Title</h3>
<p>Test contents</p>
<h4>TEST</h4>
</div>
In [6]:
soup.find('div', id='lower')
Out[6]:
<div class="test" custom="nice" id="lower">
<p>Test Test Test 1</p>
<p>Test Test Test 2</p>
<p>Test Test Test 3</p>
</div>
In [7]:
soup.find('div', class_='test')
Out[7]:
<div class="test" custom="good" id="upper">
<h3 class="test2" title="Good Content Title">Contents Title</h3>
<p>Test contents</p>
<h4>TEST</h4>
</div>
In [8]:
attrs = { 'id': 'upper', 'class': 'test' }
attrs2 = {"class": "btn btn_view", "data-clk": "sug.cxlink", "target": "_blank"}
soup.find('div', attrs=attrs)
Out[8]:
<div class="test" custom="good" id="upper">
<h3 class="test2" title="Good Content Title">Contents Title</h3>
<p>Test contents</p>
<h4>TEST</h4>
</div>

find_all 함수

  • find가 조건에 만족하는 하나의 tag만 검색한다면, find_all은 조건에 맞는 모든 tag를 리스트로 반환
In [9]:
soup.find_all('div', class_='test')
Out[9]:
[<div class="test" custom="good" id="upper">
 <h3 class="test2" title="Good Content Title">Contents Title</h3>
 <p>Test contents</p>
 <h4>TEST</h4>
 </div>,
 <div class="test" custom="nice" id="lower">
 <p>Test Test Test 1</p>
 <p>Test Test Test 2</p>
 <p>Test Test Test 3</p>
 </div>]

get_text 함수

  • tag안의 value를 추출
  • 부모tag의 경우, 모든 자식 tag의 value를 추출
In [10]:
tag = soup.find('h3')
print(tag)
tag.get_text()
<h3 class="test2" title="Good Content Title">Contents Title</h3>
Out[10]:
'Contents Title'
In [11]:
tag = soup.find('p')
print(tag)
tag.get_text()
<p>Test contents</p>
Out[11]:
'Test contents'
In [12]:
tag = soup.find('div', id='upper')
print(tag)
tag.get_text()
<div class="test" custom="good" id="upper">
<h3 class="test2" title="Good Content Title">Contents Title</h3>
<p>Test contents</p>
<h4>TEST</h4>
</div>
Out[12]:
'\nContents Title\nTest contents\nTEST\n'

attribute 값 추출하기

  • 경우에 따라 추출하고자 하는 값이 attribute에도 존재함
  • 이 경우에는 검색한 tag에 attribute 이름을 [ ]연산을 통해 추출가능
  • 예) div.find('h3')['title']
In [13]:
type(tag)
Out[13]:
bs4.element.Tag
In [14]:
tag = soup.find('h3')
print(tag)
tag['title']
<h3 class="test2" title="Good Content Title">Contents Title</h3>
Out[14]:
'Good Content Title'